原始项目地址:Finance-Python(https://github.com/wegamekinglc/Finance-Python);
python setup.py install
或者,pip install finance-python
相关依赖请见主目录下
requirements
文件夹。
In [18]:
from PyFin.Math.Accumulators import Latest
exp1 = Latest('x')
exp1
Out[18]:
上面可以看到 exp1
是一个 accumulator
的实例。
In [19]:
# 1st round
exp1.push({'x': 1})
print("Value after 1st round: {0}".format(exp1.value))
# 2nd round
exp1.push({'x': 2})
print("Value after 2nd round: {0}".format(exp1.value))
# repeate
print("Do nothing: {0}".format(exp1.value))
# 3rd and 4th round
exp1.push({'x': 3})
exp1.push({'x': 4})
print("Value after 3rd/4th round: {0}".format(exp1.value))
In [20]:
from PyFin.Math.Accumulators import MovingAverage
ma = MovingAverage(x='x', window=2)
values = [1, 2, 3, 4, 5]
for i, x in enumerate(values):
ma.push({'x': x})
print("{0}: {1}".format(i, ma.value))
In [21]:
import numpy as np
from PyFin.Math.Accumulators import MovingVariance
from PyFin.Math.Accumulators import Sqrt
np.random.seed(47)
ret_simulated = 0.0005 + np.random.randn(2000) / 100.
ret_mean = MovingAverage(x='x', window=250)
ret_std = Sqrt(MovingVariance(x='x', window=250)) # Compounded accumlator is used here
sharp = ret_mean / ret_std # dividing can be used for accumulators
sharp
Out[21]:
输入数据:
In [22]:
sharp_series = []
for ret in ret_simulated:
sharp.push({'x': ret})
sharp_series.append(sharp.value)
把数据画出来出来:
In [23]:
%matplotlib inline
import pandas as pd
df = pd.DataFrame({'returns': ret_simulated.cumsum(), 'sharp': sharp_series})
df[250:].plot(secondary_y='sharp', figsize=(12, 6))
Out[23]:
In [24]:
from PyFin.Math.Accumulators import MovingCorrelation
ma20 = MovingAverage(x='x', window=20)
ma50 = MovingAverage(x='x', window=50)
corr = MovingCorrelation(window=250, x=ma20, y=ma50)
corr
Out[24]:
In [25]:
ma20_series = []
ma50_series = []
corr_series = []
for ret in ret_simulated:
ma20.push({'x': ret})
ma50.push({'x': ret})
corr.push({'x': ret})
ma20_series.append(ma20.value)
ma50_series.append(ma50.value)
corr_series.append(corr.value)
In [26]:
df = pd.DataFrame({'ma20': ma20_series, 'ma50': ma50_series, 'corr': corr_series})
df[300:].plot(secondary_y='corr', figsize=(12, 6))
Out[26]:
In [27]:
from PyFin.api import MA
from PyFin.examples.datas import sample_data
In [28]:
sample_data
Out[28]:
In [29]:
ma2 = MA(2, 'close')
In [30]:
ma2.transform(sample_data, category_field='code')
Out[30]:
In [31]:
ma2 = MA(2, 'close')
In [32]:
ma2.transform(sample_data)
Out[32]:
In [ ]: